package aftersale

import (
	"context"
	// "fmt"
	"strings"
	"time"

	"mall/common/globalkey"
	"mall/common/resultx"
	"mall/common/utils/pointy"
	"mall/service/order/model"
	"mall/service/order/rpc/internal/svc"
	"mall/service/order/rpc/types/order"

	// "github.com/sirupsen/logrus"
	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateAfterSaleLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdateAfterSaleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateAfterSaleLogic {
	return &UpdateAfterSaleLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 退款流程：待处理（同意）-->待退款（退款）-->售后成功
// 退货流程：待处理（同意）-->待退货（已收货）-->待退款（退款）-->售后成功
// 换货流程：待处理（同意）-->待退货（已收货）-->待换货（推送erp通知发货）-->已发货待签收（已发货）-->已签收（用户已签收）-->售后成功
func (l *UpdateAfterSaleLogic) UpdateAfterSale(in *order.AfterSaleInfo) (*order.UpdateAfterSaleResp, error) {
	// logrus.Info(fmt.Sprintf("AfterSaleInfo: %+v", in))
	if in.Id == nil || *in.Id == 0 {
		return nil, resultx.StatusError(resultx.AFTER_SALE_ID_REQUIRED, "")
	}

	//查询后修改
	res, err := l.svcCtx.AfterSaleRequest.FindOneNoCache(l.ctx, nil, *in.Id)
	if err != nil {
		if err == model.ErrNotFound {
			return nil, resultx.StatusError(resultx.AFTER_SALE_ID_INVALID, "")
		}

		return nil, err
	}

	afterSaleType := uint32(res.AfterSaleType)
	var status uint32
	var isRefund, isBarter bool
	if in.Status != nil {
		switch *in.Status {
		case globalkey.AfterSaleProcessCanceled: //用户已取消申请
			status = globalkey.AfterSaleStatusClosed
		case globalkey.AfterSaleProcessApproved: //同意
			if afterSaleType == globalkey.AfterSaleTypeRefund {
				status = globalkey.AfterSaleStatusAwaitRefund
			} else if afterSaleType == globalkey.AfterSaleTypeReturn || afterSaleType == globalkey.AfterSaleTypeBarter {
				status = globalkey.AfterSaleStatusAwaitReturn
			}
		case globalkey.AfterSaleProcessRejected: //驳回
			status = globalkey.AfterSaleStatusRejected
			if in.ReasonForRefusal != nil && len(strings.TrimSpace(*in.ReasonForRefusal)) > 0 {
				res.ReasonForRefusal = strings.TrimSpace(*in.ReasonForRefusal)
			}
		case globalkey.AfterSaleProcessReturned: //已退回
			if afterSaleType == globalkey.AfterSaleTypeReturn || afterSaleType == globalkey.AfterSaleTypeBarter {
				status = globalkey.AfterSaleStatusAwaitConfirm
			}
		case globalkey.AfterSaleProcessTimeouted: //超时自动关闭
			status = globalkey.AfterSaleStatusTimeouted
			// Todo: 定时任务设置 售后申请超时
		case globalkey.AfterSaleProcessConfirmed: // 仓库已接收退货
			if afterSaleType == globalkey.AfterSaleTypeReturn {
				status = globalkey.AfterSaleStatusAwaitRefund
			}
			if afterSaleType == globalkey.AfterSaleTypeBarter {
				status = globalkey.AfterSaleStatusAwaitBarter
				isBarter = true
			}
		case globalkey.AfterSaleProcessRefunded: //已退款
			status = globalkey.AfterSaleStatusSuccess
			isRefund = true
		case globalkey.AfterSaleProcessShipped: //仓库已发换货
			status = globalkey.AfterSaleStatusShipped
			// Todo: 换货 补发 需要在订单里 追加新的包裹信息
		case globalkey.AfterSaleProcessBartered: //用户已签收换货
			status = globalkey.AfterSaleStatusSuccess
		}
	}
	res.UpdatedAt = time.Now()
	res.Status = uint8(status)
	err = l.svcCtx.AfterSaleRequest.Update(l.ctx, nil, res)
	if err != nil {
		return nil, err
	}

	return &order.UpdateAfterSaleResp{
		Id:       &res.ID,
		UserId:   &res.UserID,
		IsRefund: pointy.GetPointer(isRefund),
		IsBarter: pointy.GetPointer(isBarter),
	}, nil
}
